package com.ry.est.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ry.est.constants.Constants;
import com.ry.est.service.SmsVerifyCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsVerifyCodeServiceImpl implements SmsVerifyCodeService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void sendVerifyCode(String phone, Integer codeType) {
        if (Constants.Sms.TYPE_REGIST_OR_LOGIN.equals(codeType)){
            sendLoginVerifyCode(phone);
        }else if (Constants.Sms.TYPE_UP_PASS.equals(codeType)){
            sendUpdateVerifyCode(phone);
        }else if (Constants.Sms.TYPE_NOTICE.equals(codeType)){
            sendNoticeVerifyCode(phone);
        }
    }

    @Override
    public String getLoginVerifyCode(String phone) {
        String redisSmsKey = getRedisSmsKey(phone);
        String VerifyCode = redisTemplate.opsForValue().get(redisSmsKey);
        return VerifyCode;
    }

    @Override
    public void removeLoginVerifyCode(String phone) {
        String redisSmsKey = getRedisSmsKey(phone);
        redisTemplate.delete(redisSmsKey);
    }

    private String getRedisSmsKey(String phone){
        return  Constants.Redis.PREFIX_SMS+phone;
    }

    private void sendLoginVerifyCode(String phone) {
        //根据手机号获取验证码
        String redisSmsKey = getRedisSmsKey(phone);
        String verifyCode = getLoginVerifyCode(redisSmsKey);
        //如果获取值不为空，直接return，不作处理
        if (!Objects.isNull(verifyCode)){
            return;
        }
        //生成6位随机的验证码
        verifyCode = RandomUtil.randomNumbers(6);
        log.info(verifyCode);
        //发送短信
        sendSms(null,null,null);
        //保存到redis缓存中
        redisTemplate.opsForValue().set(redisSmsKey,verifyCode,5, TimeUnit.MINUTES);
        //保存日志

    }

    private String sendSms(String phone,String templateCode,String data){
        return null;
    }

    private void sendNoticeVerifyCode(String phone) {

    }

    private void sendUpdateVerifyCode(String phone) {

    }
}
